//fetch.html
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

let fs = require('fs');

//方式1
app.use(express.json());
app.use(express.urlencoded({extended:true}));
//方式2  两种方式都可以，下面的写法不对
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended:true}));
//app.use(express.static(__dirname));这种不对

//封装一个方法
function read(cb){//用来读取数据的
	fs.readFile('./book.json','utf-8',function (err,data){
		if(err || data.length == 0){
			cb([]);  //如果有错误或者文件没长度，就是空数组
		}else{
			cb(JSON.parse(data));  //将读出来的内容转化成对象
		}
	});
};

app.get('/category',(req,res)=>{
    res.json({
        menuList:[
            {pid:-1,name:'服装',id:1,auth:'clothing'},
            {pid:1,name:'男装',id:4,auth:'men-wear'},
            {pid:1,name:'女装',id:5,auth:'women-wear'},
            {pid:5,name:'裙子',id:6,auth:'skirt'},
            {pid:4,name:'衬衫',id:7,auth:'shirt'},
            {pid:-1,name:'酒类',id:2,auth:'liquor'},
            // {pid:-1,name:'医药',id:3,auth:'medicine'},
        ]
    })
});




app.get('/book',function(req,res){
	let id = parseInt(req.query.id);
	if(!isNaN(id)){//查询一个，获取与id对应的图书，因为0是false会走else，所以加一个条件
		read(function(books){
			let book = books.find(item=>item.bookId===id);//只找一个找到后就返回了
			if(!book) book = {}; //如果没找到则是undefined
			res.json(book);
		});
	}else{//获取所有图书
		read(function(books){
			res.json(books.reverse());
		})
	}
});

app.post('/add',function(req,res){
  //接收到前端传来的数据
  console.log(req.body)
  res.send(req.body);
})


app.get('/',function(req,res){
  //返给前端页面
  res.sendFile('./fetch.html',{root:__dirname})
})

app.listen(3010,()=>{
  console.log(`访问路径：http://localhost:3010/`)
});